var zing = {
    init: function(){
        var songs = this.extractSongs();
        
        if( songs.length > 0 ){
            this.injectDownloadButton(songs);

        }
    },
    extractSongs: function(){
        var matches = document.body.innerHTML.match(/<a title="Download (.*?)" href="(.*?)"/igm);
        var songs = [];
        
        for(var index = 0; index < matches.length; index++){
            var song = {};
            var parts = /<a title="Download (.*?)" href="(.*?)"/igm.exec(matches[index]);
            
            song.url = $.trim(parts[2]);
            
            songParts = parts[1].split('-');
            
            song.singer = $.trim(songParts[1]);
            song.title = $.trim(songParts[0]);
            
            songs[index] = song;
            
        };
        return songs;
    },
    injectDownloadButton: function(songs){
        var newButton = $('<li class="fleft" style="cursor:pointer"><img src="'  + chrome.extension.getURL('icon24.png')  + '" /></li>');
        newButton.click(function(){
            var proceed = true;
            if( songs.length > 1){
                if( !confirm('Có nhiều tab sẽ được mở. Bạn có chắc chắn muốn download toàn bộ album khong?')){
                    proceed = false;
                }
            }
            if( proceed ){
                chrome.extension.sendRequest({
                    event: EVENT.DOWNLOAD_ALBUM,
                    songs: songs
                });
            }
        });
        $('#_btnShareShw>ul').append(newButton);
    }
    
    
};

zing.init();